package com.example.doubledatasource.converter;

import com.example.doubledatasource.dto.UserDTO;
import com.example.doubledatasource.entity.User;
import com.example.doubledatasource.vo.UserVO;
import org.mapstruct.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 用户对象转换器 - 使用MapStruct
 * 负责User、UserDTO、UserVO之间的转换
 *
 * @author example
 * @since 1.0.0
 */
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING,
        nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
        unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserConverter {

    DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * Entity转VO
     */
    @Mapping(target = "createTimeStr", source = "createTime", qualifiedByName = "formatDateTime")
    @Mapping(target = "updateTimeStr", source = "updateTime", qualifiedByName = "formatDateTime")
    UserVO toVO(User user);

    /**
     * DTO转Entity
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "createTime", expression = "java(java.time.LocalDateTime.now())")
    @Mapping(target = "updateTime", expression = "java(java.time.LocalDateTime.now())")
    User toEntity(UserDTO dto);

    /**
     * 更新Entity（用于更新操作）
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "createTime", ignore = true)
    @Mapping(target = "updateTime", expression = "java(java.time.LocalDateTime.now())")
    void updateEntity(@MappingTarget User user, UserDTO dto);

    /**
     * Entity列表转VO列表
     */
    List<UserVO> toVOList(List<User> users);

    /**
     * 格式化日期时间
     */
    @Named("formatDateTime")
    default String formatDateTime(LocalDateTime dateTime) {
        return dateTime != null ? dateTime.format(DATE_TIME_FORMATTER) : null;
    }
}
